from django import forms
from django.contrib.auth.models import User


class LoginForm(forms.Form):
    """登录表单"""
    username = forms.CharField(label="用户名", max_length=100, widget=forms.TextInput(attrs={
        'class': 'input', 'placeholder': '用户名/邮箱'}))
    password = forms.CharField(label="密码", min_length=4, widget=forms.PasswordInput(attrs={
        'class': 'input', 'placeholder': '密码'}))

    def clean(self):
        username = self.cleaned_data.get("username")
        password = self.cleaned_data.get("password")
        if username and password:
            if username == password:
                raise forms.ValidationError("用户名和密码不能相同")
        return password


class RegisterForm(forms.ModelForm):
    """注册表单"""
    email = forms.CharField(label="邮箱", max_length=100, widget=forms.EmailInput(attrs={
        'class': 'input', 'placeholder': '用户名/邮箱'}))
    password = forms.CharField(label="密码", min_length=4, widget=forms.PasswordInput(attrs={
        'class': 'input', 'placeholder': '密码'}))
    password1 = forms.CharField(label="确认密码", min_length=4, widget=forms.PasswordInput(attrs={
        'class': 'input', 'placeholder': '确认密码'}))

    class Meta:
        model = User
        fields = ['email', 'password']

    def clean_username(self):
        """用户名验证"""
        email = self.cleaned_data.get("email")
        if User.objects.filter(email=email).exists():
            raise forms.ValidationError("邮箱已存在")
        return email

    def clean_password1(self):
        """密码验证"""
        password1 = self.cleaned_data.get("password1")
        if password1 != self.cleaned_data.get("password"):
            raise forms.ValidationError("两次密码输入不一致")
        return password1
